using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Globalization;

namespace Camalon.Drawing
{
	public class ColorIntensityConverter:ExpandableInstanceConverter
	{
		//The code copied from SizeScaleCOnverter and width and height values renamed...!
		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{
			try
			{
				if ( value is string ) 
				{
					string sVal = (string)value;
					sVal = sVal.Trim();
					if( sVal.ToLower().IndexOf("empty") != -1) return ColorIntensity.Empty;

			
					string[] args = sVal.Split(';');
					if( args.Length != 2) throw new InvalidOperationException("Invalid value");
				
					char[] percentChar = culture.NumberFormat.PercentSymbol.ToCharArray();
					string position  = args[0].Trim();	string[] x_ = position.Split(percentChar);	position = x_[0];
					string intensity  = args[1].Trim();	string[] y_ = intensity.Split(percentChar);	intensity = y_[0];
					return new ColorIntensity( float.Parse( position )/100f,float.Parse( intensity )/100f);
				}

				//return context.PropertyDescriptor.GetValue( context.Instance );
				return base.ConvertFrom (context, culture, value);
			}
			catch(Exception e)
			{
				FileWatcher.WriteLine( "ColorIntensity:ConvertFrom -->" + e.Message +"\r\n"+e.StackTrace);
				throw e;
			}
		}

		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{
			try
			{
				if( value is ColorIntensity )
				{
					ColorIntensity m = (ColorIntensity) value;

					if (destinationType == typeof(string)) 
					{
						if( m.IsEmpty) return "Empty";
						string percent = culture.NumberFormat.PercentSymbol;
						return String.Format( "{0}{2}; {1}{2}", m.Position*100f,m.Intensity*100f, percent);
					}

					if (destinationType == typeof(InstanceDescriptor) ) 
					{
						ConstructorInfo ctor = typeof(ColorIntensity).GetConstructor(new Type[] {typeof(float), typeof(float)});
						if (ctor != null) return new InstanceDescriptor(ctor, new object[] {m.Position,m.Intensity});
					}

				}

				return base.ConvertTo (context, culture, value, destinationType);
			}
			catch( Exception e)
			{
				FileWatcher.WriteLine( "ColorIntensity:ConvertTo -->" + e.Message +"\r\n"+e.StackTrace);
				throw e;
			}
		}


	}

}
